package ltu.m7011e.client.presenter;

import java.util.List;

import ltu.m7011e.client.LinkServiceRequester;
import ltu.m7011e.client.XMLParser.Parser;
import ltu.m7011e.client.event.GoToMainViewEvent;
import ltu.m7011e.client.event.ShowPostBoxEvent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;

public class PostLinkPresenter implements Presenter {  

	public interface Display {
		HasClickHandlers getPostLinkButton();
		HasClickHandlers getClosePostButton();
		HasValue<String> getUrlField();
		HasValue<String> getDescriptionField();
		String getLinkCat();
		DialogBox getPostDialogBox();
		void setData(List<String> data);
		Widget asWidget();
	}

	private final LinkServiceRequester linkServiceRequester;
	private final HandlerManager eventBus;
	private final Display display;

	public PostLinkPresenter(LinkServiceRequester linkRequester, HandlerManager eventBus, Display view) {
		this.linkServiceRequester = linkRequester;
		this.eventBus = eventBus;
		this.display = view;
		bind();
		GWT.log("PostLinkPresenter - Constructor Called");
	}

	public void bind() {
		display.getPostLinkButton().addClickHandler(new ClickHandler() {   
			public void onClick(ClickEvent event) {
				GWT.log("Click on PostLinkButton !");
				String linkUrl = PostLinkPresenter.this.display.getUrlField().getValue();
				String linkDescription = PostLinkPresenter.this.display.getDescriptionField().getValue();
				String linkCategory = PostLinkPresenter.this.display.getLinkCat();
				Document xmlLinkToSend = Parser.BuildLinkFromInfo(linkUrl, linkCategory, linkDescription, "unused");
				GWT.log("XmlToSend = "+xmlLinkToSend.toString());
				linkServiceRequester.postLink(xmlLinkToSend);
				eventBus.fireEvent(new GoToMainViewEvent());
			}
		});

		display.getClosePostButton().addClickHandler(new ClickHandler() {   
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new GoToMainViewEvent());
			}
		});

	}

	public void go(final HasWidgets container) {

		container.clear();
		container.add(display.asWidget());
	}

}
